今天要講ScrollView的使用方法,並把畫面進度推到60%,首先我們最上面會有一個CollectionView,之後在最底下會有一個ScrollView,裡面包含兩個CollectionView,除了可以左右捲動之外還可以上下捲動。
https://youtube.com/shorts/hIgYqcTS40M?feature=share
這邊需要了解到 ScrollView是有兩種Layout的,一個是Frame Layout Guide跟ContentLayout Guide
你的ScrollView有多大,這邊就是正常給,像是Equal Height Equal Weight等等之類的。
這邊就是你要設定好你元件的大小,ScrollView才會正常運作:
所以我裡面包含的兩個CollectionView的寬跟高都是跟ScrollView 1:1
那剩下就是把Trailing Leading Top Space等等拉好
先設定好ScrollView:
scvOfRestaurantAndMore?.delegate = self
scvOfRestaurantAndMore?.isPagingEnabled = true
拉好之後我們把 CollectionView 設定成 horizontal 因為我們要左右滑動,然後把Cell都註冊進去:
collectionViewRestaurant.tag = 0
collectionViewRestaurant.dataSource = self
collectionViewRestaurant.delegate = self
collectionViewRestaurant.register(ResaurantCollectionViewCell.loadFromNib(), forCellWithReuseIdentifier: ResaurantCollectionViewCell.identifier)
collectionViewRestaurant_2.tag = 1
collectionViewRestaurant_2.delegate = self
collectionViewRestaurant_2.dataSource = self
collectionViewRestaurant_2.register(TypeCollectionViewCell.loadFromNib(), forCellWithReuseIdentifier: TypeCollectionViewCell.identifer)
moreImformationsCollectionView.tag = 2
moreImformationsCollectionView.delegate = self
moreImformationsCollectionView.dataSource = self
moreImformationsCollectionView.register(MoreImformationsCollectionViewCell.loadFromNib(), forCellWithReuseIdentifier: MoreImformationsCollectionViewCell.identifier)
extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch collectionView.tag {
case 0:
return 4
case 1:
return 4
case 2:
return 4
default:
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch collectionView.tag {
case 0:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ResaurantCollectionViewCell.identifier, for: indexPath) as!
ResaurantCollectionViewCell
cell.imgCell.image = UIImage(named: foodType[indexPath.row])
return cell
case 1:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TypeCollectionViewCell.identifer, for: indexPath) as!
TypeCollectionViewCell
cell.imgCell.image = UIImage(named: foodType[indexPath.row])
return cell
case 2:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MoreImformationsCollectionViewCell.identifier, for: indexPath) as!
MoreImformationsCollectionViewCell
cell.imgCell.image = UIImage(named: foodType[indexPath.row])
return cell
default:
return UICollectionViewCell()
}
return UICollectionViewCell()
}
}